﻿using B.S.BasicData.Api.Read.Application.Command;
using B.S.BasicData.Api.Read.DTO;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore.Infrastructure.Internal;

namespace B.S.BasicData.Api.Read.Application.Handler
{
    public class GetUserRoleMenuHandler : IRequestHandler<GetUserRoleMenuCommand, ApiResult<List<UserRoleMenuDTO>>>
    {
        private readonly IBaseRepository<RoleMenuModel> roleMenuRepo;
        private readonly IBaseRepository<MenuModel> menuRepo;

        public GetUserRoleMenuHandler(IBaseRepository<RoleMenuModel> roleMenuRepo,IBaseRepository<MenuModel> menuRepo)
        {
            this.roleMenuRepo = roleMenuRepo;
            this.menuRepo = menuRepo;
        }
        public Task<ApiResult<List<UserRoleMenuDTO>>> Handle(GetUserRoleMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<UserRoleMenuDTO>> res = new ApiResult<List<UserRoleMenuDTO>>();
            var list = request.Rle.Split(',').ToList();
            var rolemenuQuery = roleMenuRepo.GetAll();
            List<int> model = new List<int>();
            foreach (var item in list)
            {
                var mids = rolemenuQuery.Where(x => x.Rid == Convert.ToInt32(item)).Select(x => x.Mid).ToList();
                model.AddRange(mids);
            }
            var menuQuery = menuRepo.GetAll().Where(x => !x.IsDelete);
            var data = Find(0,menuQuery.ToList(),model);
            res.Code = ApiEnum.Success;
            res.Msg = "成功";
            res.Data = data;
            return Task.FromResult(res);
        }
        private List<UserRoleMenuDTO> Find(int id,List<MenuModel> ids,List<int> mid)
        {
            var res = ids.Where(x => x.Pid == id && mid.Contains(x.Id)).ToList();
            List<UserRoleMenuDTO> menus = new List<UserRoleMenuDTO>();
            foreach (var item in res)
            {
                menus.Add(new UserRoleMenuDTO
                {
                    MenuUrl = item.Url,
                    MenuName=item.MenuName,
                    Children=Find(item.Id,ids,mid),
                });
            }
            return menus;
        }
    }
}
